package com.project.market.service.impl;

import com.github.pagehelper.PageHelper;
import com.project.market.db.domain.*;
import com.project.market.db.mapper.*;
import com.project.market.service.AdminGoodsService;
import com.project.market.util.MybatisUtil;
import com.project.market.vo.CatAndBrandVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminGoodsServiceImpl implements AdminGoodsService {
    @Override
    public List<MarketGoods> list(String page, String limit, String goodsSn, String name, String sort, String order, String goodsId) {
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        //条件一共有三个 name goodsSn goodsId
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andIdEqualTo(Integer.parseInt(goodsId));
        }
        goodsExample.setOrderByClause(sort + " " + order);
        //分页的代码需要紧跟着查询
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketGoods> marketGoodsList = goodsMapper.selectByExample(goodsExample);
        session.commit();
        session.close();
        return marketGoodsList;
    }

    @Override
    public Map<String, Object> catAndBrand() {
        //当前的品牌信息和类目信息 查询两张表 brand category表
        SqlSession session = MybatisUtil.getSession();
        MarketBrandMapper brandMapper = session.getMapper(MarketBrandMapper.class);
        MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);
        List<MarketBrand> marketBrands = brandMapper.selectByExample(new MarketBrandExample());
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(new MarketCategoryExample());
        session.commit();
        session.close();
        ///但是查询出来的数据不是前端需要的数据格式，所以，需要进行转换适配的工作
        //先封装brand
        List<CatAndBrandVo> brandListVO = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            brandListVO.add(new CatAndBrandVo(marketBrand.getId(), marketBrand.getName()));
        }
        //brand处理完毕
        //处理categorylist
        //尝试对获取到的category list集合根据pid进行分组，分组过后，相同的pid的数据在一组
        //pid=0  一级类目   pid=1005000的类目均是编号为1005000的二级类目
        List<CatAndBrandVo> categoryListVO = new ArrayList<>();

        Map<Integer, List<MarketCategory>> groupByPidCategory = groupByPid(marketCategories);
        List<MarketCategory> l1Categories = groupByPidCategory.get(0);
        for (MarketCategory l1Category : l1Categories) {
            //当前类目下的二级类目
            Integer id = l1Category.getId();
            CatAndBrandVo l1CategoryVO = new CatAndBrandVo(l1Category.getId(), l1Category.getName());
            categoryListVO.add(l1CategoryVO);
            //用来去保存children
            List<CatAndBrandVo> childrenVO = new ArrayList<>();
            List<MarketCategory> l2CategoriesOfL1 = groupByPidCategory.get(id);
            if (l2CategoriesOfL1 == null) continue;
            for (MarketCategory l2Category : l2CategoriesOfL1) {
                if (l2Category == null) continue;
                childrenVO.add(new CatAndBrandVo(l2Category.getId(), l2Category.getName()));

            }
            l1CategoryVO.setChildren(childrenVO);
        }
        Map<String, Object> resultVO = new HashMap<>();
        resultVO.put("brandList", brandListVO);
        resultVO.put("categoryList", categoryListVO);
        return resultVO;
    }

    @Override
    public Object create(MarketGoods goods, List<MarketGoodsProduct> products, List<MarketGoodsSpecification> specifications, List<MarketGoodsAttribute> attributes) {
        //商品上架，需要做哪些事情？说白了便是插入4张表数据
        goods.setSortOrder((short) 100);
        goods.setAddTime(LocalDateTime.now());
        goods.setUpdateTime(LocalDateTime.now());
        goods.setDeleted(false);
        //从众多的商品库存中选择出一个最低的价格出来，赋值给当前的零售价格
        BigDecimal retailPrice = products.get(0).getPrice();
        for (int i = 1; i < products.size(); i++) {
            //首先获取products中第一个产品的价格，赋值给一个变量
            //后续遍历其他的产品，如果发现有更小的价格，那么便把更小的价格赋值给当前的变量，最终该变量存储的便是最低价格
            if (retailPrice.compareTo(products.get(i).getPrice()) == 1) {
                //表示的是retailPrice大于后面的价格，把后面的价格赋值给retailPrice
                retailPrice = products.get(i).getPrice();
            }

        }
        goods.setRetailPrice(retailPrice);
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        //以下4张表的插入应该满足同时插入成功、同时失败，所以需要在一个事务内
        try {
            goodsMapper.insert(goods);
            //随后插入products、specification、attribute表
            for (MarketGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setAddTime(LocalDateTime.now());
                product.setUpdateTime(LocalDateTime.now());
                product.setDeleted(false);
                productMapper.insert(product);
            }
            //继续插入规格
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setAddTime(LocalDateTime.now());
                specification.setUpdateTime(LocalDateTime.now());
                specification.setDeleted(false);
                specificationMapper.insert(specification);
            }
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setAddTime(LocalDateTime.now());
                attribute.setUpdateTime(LocalDateTime.now());
                attribute.setGoodsId(goods.getId());
                attributeMapper.insert(attribute);
            }

        } catch (Exception e) {
            return null;
        }
        session.commit();
        session.close();
        return goods;
    }

    private Map<Integer, List<MarketCategory>> groupByPid(List<MarketCategory> marketCategories) {
        //创建一个map
        Map<Integer, List<MarketCategory>> result = new HashMap<>();
        //遍历全部的category集合信息
        for (MarketCategory marketCategory : marketCategories) {
            //尝试从map中，根据当前遍历的category的pid值，从map中获取该集合
            List<MarketCategory> categoryListOfOnPid = result.get(marketCategory.getPid());
            //如果第一次操作，那么获取到的肯定是null，如果是null，那么我们创建一个list，并且把list put到map中
            if (categoryListOfOnPid == null) {
                categoryListOfOnPid = new ArrayList<>();
                result.put(marketCategory.getPid(), categoryListOfOnPid);
            }
            //随即把符合条件的类目放入到当前list中
            categoryListOfOnPid.add(marketCategory);
        }
        return result;
    }
}
